/*
 *     This file is part of Mobile GPS Logger.
 *
 *     Mobile GPS Logger is free software: you can redistribute it and/or
 *     modify it under the terms of the GNU General Public License as
 *     published by the Free Software Foundation, either version 3 of the
 *     License, or (at your option) any later version.
 *
 *     Mobile GPS Logger is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU General Public License v3 for more details.
 *
 *     You should have received a copy of the GNU General Public License v3
 *     along with Mobile GPS Logger. If not, see <http://www.gnu.org/licenses/>.
 */

package cx.ath.skyflyer.gpslog.util;

import java.util.NoSuchElementException;

/**
 *
 * @author Ahti Legonkov
 */
public class Tokenizer {

	/**
	 * Constructs a new tokenizer for the given string using comma and star as
     * delimiters.
	 * @param m_String String to be tokenized.
	 */
	public Tokenizer(String s) {
        this(s, new char[] {',', '*'});
	}

	/**
	 * Constructs a new tokenizer for the given string using the array of
     * characters given in delimiters.
	 * @param m_String String to be tokenized.
     * @param delimiters array of the field delimiter characters.
	 */
    public Tokenizer(String s, char[] delimiters) {
		this.string = s;
        this.delimiters = delimiters;
		this.currentPosition = 0;
		this.nextPosition = nextDelimiterIndex();
    }
	/**
	 * @return true, if there is a at least one more token.
	 */
	public boolean hasNext() {
		return currentPosition < string.length();
	}

	/**
	 *
	 * @return Next token
	 * @throws NoSuchElementException If there are no tokens remaining.
	 */
	public String next() throws NoSuchElementException {

		if (!hasNext())
			throw new NoSuchElementException();

		String next = string.substring(currentPosition, nextPosition);

		currentPosition = nextPosition + 1;
        nextPosition = nextDelimiterIndex();

		return next;
	}

    private int nextDelimiterIndex() {
        int res = string.indexOf(delimiters[0], currentPosition);
        if (res == -1)
            res = string.length();
        
        for (int i = 1; i < delimiters.length; ++i) {
            int pos = string.indexOf(delimiters[i], currentPosition);
            if (pos != -1 && pos < res) {
                res = pos;
            }
        }

        return res;
    }

	private final String string;
	private final char[] delimiters;
	private int currentPosition;
	private int nextPosition;

}